package com.dhcc.utils.servletrequest;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import com.dhcc.utils.Operator;

public class IpOperator implements Operator<ServletRequest> {

	@Override
	public Object invoke(String operator, ServletRequest first, Object[] args) {
		if(first == null || !(first instanceof HttpServletRequest)){
			return "unknown";
		}
		HttpServletRequest req = (HttpServletRequest)first;
		String ip = req.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getRemoteAddr();
		}
		return ip;
	}

}
